package com.sky.service.common.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.exception.ParameterInvalidException;
import com.sky.mapper.common.ShortUrlMapper;
import com.sky.mapper.courier.CourierMapper;
import com.sky.mapper.courier.CourierTradeOrderMapper;
import com.sky.pojo.Courier;
import com.sky.pojo.CourierTradeOrder;
import com.sky.service.common.CommonService;
import com.sky.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 公共业务接口实现
 * @author zgp
 * @version V1.0
 * @date 2025-02-20 16:48
 */
@Service
public class CommonServiceImpl implements CommonService {
    @Autowired
    private CourierMapper courierMapper;
    @Autowired
    private CourierTradeOrderMapper courierTradeOrderMapper;
    @Autowired
    private ShortUrlMapper shortUrlMapper;


    @Override
    public String getRouteInfo(Long tradeNo, Integer courierId, LocalDateTime expire) {
        if(ObjectUtil.isNull(tradeNo)
                || ObjectUtil.isNull(courierId)
                || LocalDateTime.now().isAfter(expire)){
            throw new ParameterInvalidException(MessageConstant.PARAMES_IS_INVALID);
        }
        // 查询骑手经纬度位置
        List<Courier> couriers = courierMapper.selectByIds(List.of(courierId));
        if(CollUtil.isEmpty(couriers)){
            throw new BaseException("骑手不存在");
        }
        String curLnglat = couriers.get(0).getCurLocation();
        // 查询商家经纬度位置
        CourierTradeOrder courierTradeOrder = courierTradeOrderMapper.selectByTradeNo(tradeNo);
        if(ObjectUtil.isNull(courierTradeOrder)){
            throw new BaseException("运单不存在");
        }
        String shopLnglat = MapUtils.addressToLnglat(courierTradeOrder.getShopAddress());
        // 查询用户经纬度位置
        String customerLnglat = MapUtils.addressToLnglat(courierTradeOrder.getCustomerAddress());
        return customerLnglat + "_" + shopLnglat + "_" + curLnglat;
    }

    @Override
    public String parseShortUrl(String code) {
        return shortUrlMapper.selectFullUrlByShortCode(code);
    }
}
